from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import os
import json

app = Flask(__name__)
CORS(app)

# 配置文件上传路径
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 存储翻译数据的文件路径
TRANSLATION_DATA_FILE = 'translation_data.json'

# 初始化翻译数据文件
if not os.path.exists(TRANSLATION_DATA_FILE):
    with open(TRANSLATION_DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump([], f)

@app.route('/api/texts', methods=['GET'])
def get_texts():
    """获取所有文本及其翻译"""
    with open(TRANSLATION_DATA_FILE, 'r', encoding='utf-8') as f:
        data = json.load(f)
    return jsonify(data)

@app.route('/api/texts', methods=['POST'])
def save_text():
    """保存翻译文本"""
    text_data = request.json
    with open(TRANSLATION_DATA_FILE, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 检查是否已存在该文本
    for i, item in enumerate(data):
        if item['id'] == text_data['id']:
            data[i] = text_data
            break
    else:
        data.append(text_data)
    
    with open(TRANSLATION_DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    return jsonify({'status': 'success'})

@app.route('/api/upload', methods=['POST'])
def upload_file():
    """上传文件"""
    if 'file' not in request.files:
        return jsonify({'error': '没有文件上传'}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '没有选择文件'}), 400
    
    if file:
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)
        
        # 读取文件内容
        texts = []
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                for i, line in enumerate(lines):
                    line = line.strip()
                    if line:
                        # 假设文件格式为: 英文原文\n中文翻译\n...
                        # 尝试解析已有的翻译
                        translation = ''
                        if i + 1 < len(lines) and not lines[i + 1].strip().startswith('[') and not lines[i + 1].strip().isdigit():
                            translation = lines[i + 1].strip()
                            i += 1  # 跳过下一行
                        
                        texts.append({
                            'id': str(len(texts) + 1),
                            'english': line,
                            'chinese': translation
                        })
        except Exception as e:
            return jsonify({'error': f'文件解析错误: {str(e)}'}), 500
        
        # 保存到数据文件
        with open(TRANSLATION_DATA_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # 合并现有数据和新数据
        existing_ids = {item['id'] for item in data}
        for text in texts:
            if text['id'] not in existing_ids:
                data.append(text)
        
        with open(TRANSLATION_DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        
        return jsonify({'status': 'success', 'texts': texts})

@app.route('/api/export', methods=['GET'])
def export_data():
    """导出翻译数据"""
    return send_file(TRANSLATION_DATA_FILE, as_attachment=True, download_name='translation_export.json')

if __name__ == '__main__':
    app.run(debug=True)